package com.nbjtjc.safe.Exception;

import com.nbjtjc.common.exception.ValidateException;
import com.nbjtjc.safe.bean.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.ExpiredSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@CrossOrigin("*")
public class MyExceptionHandler {

    private static Logger logger= LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler(AuthorizationException.class)
    public Result<String> handleAuthorizationException(AuthorizationException e) {
        Result result = new Result<>();
        result.setFalse("你没有该权限");
        result.setCode(101);
        return result;
    }

    @ExceptionHandler(AuthenticationException.class)
    public Result<String> handleAuthenticationException(AuthenticationException e) {
        Result result = new Result<>();
        result.setFalse("没有登录");
        result.setCode(100);
        return result;
    }

    @ExceptionHandler(ExpiredSessionException.class)
    public Result<String> handleExpiredSessionException(ExpiredSessionException e) {
        Result result = new Result<>();
        result.setFalse("session过期");
        result.setCode(100);
        return result;
    }

    @ExceptionHandler(ValidateException.class)
    public Result handleValidatorException(ValidateException e){
        Result result = new Result<>();
        result.setFalse(e.getMessage());
        result.setCode(500);
        logger.error("参数验证错误："+e.getMessage(),e);
        return result;
    }
    @ExceptionHandler(SafeException.class)
    public Result handleSafeException(SafeException e){
        Result result = new Result<>();
        result.setFalse(e.getMessage());
        result.setCode(510);
        logger.error(e.getMessage(),e);
        return result;
    }
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        Result result = new Result<>();
        e.printStackTrace();
        result.setFalse("发生错误，可能是session过期或者其他问题:" + e.getMessage());
        result.setCode(100);
        logger.error(e.getMessage(),e);
        return result;
    }
}
